<template>
  <div class="search-container">
    <form class="search-form" action="/">
    <van-search
      v-model="searchText"
      show-action
      placeholder="请输入搜索关键词"
      background="#3296fa"
      @search="onSearch"
      @cancel="onCancel"
      @focus="isResultShow=false"
    />
  </form>

    <!-- 搜索结果 -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    ></search-result>
    <!-- /搜索结果-->
    <!--联想建议-->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></search-suggestion>
    <!--/联想建议-->
    <!-- 搜索历史记录-->
    <search-history
      v-else
      :searchHistories="searchHistories"
      @clear-search-histories="searchHistories=[]"
      @search="onSearch"
    ></search-history>
    <!-- /搜索历史记录-->
  </div>
</template>

<script>
import SearchHistory from '@/components/search-history.vue'
import SearchSuggestion from '@/components/search-suggestion.vue'
import SearchResult from '@/components/search-result.vue'
import { setItem, getItem } from '@/utils/storage'

export default {
  name: 'SearchIndex',
  components: { SearchResult, SearchSuggestion, SearchHistory },
  props: {},
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('TOUTIAO-SEARCH-HISTORIES') || []
    }
  },
  computed: {},
  watch: {
    searchHistories (val) {
      setItem('TOUTIAO-SEARCH-HISTORIES', val)
    }
  },
  created () {},
  methods: {
    onSearch (val) {
      // this.$toast(val)
      // 更新文本框内容
      this.searchText = val

      // 要求：不要有重复历史记录、最新的排在最前面
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // 渲染搜索的结果
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.search-container{
  padding-top: 54px;
  .van-search__action{
  color: #fff;
 }
  .search-form{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
